package com.spring.cloud.weather.city.service;

import com.spring.cloud.weather.city.util.XmlBuilder;
import com.spring.cloud.weather.city.vo.City;
import com.spring.cloud.weather.city.vo.CityList;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by Administrator on 2018/3/17
 */
@Service
public class CityDataServiceImpl implements CityDataService {

    /**
     * 获取城市列表
     *
     * @return List<City>
     * @throws Exception Exception
     */
    @Override
    public List<City> listCity() throws Exception {
        // 读取XML文件
        Resource resource = new ClassPathResource("citylist.xml");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), "utf-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine()) !=null) {
            stringBuilder.append(line);
        }

        bufferedReader.close();

        // XML转为Java对象
        CityList cityList = (CityList) XmlBuilder.xmlStrToOject(CityList.class, stringBuilder.toString());
        return cityList.getCityList();
    }
}
